#include "XSystem/XCore.h"
#include "GLogin.h"

// Initialize the window
GLogin::GLogin(XResourcesManager *data) : XWindow(data)
{
	// Default values
    x_positionX = 185;
    x_positionY = 150;
    x_width = 430;
    x_height = 300;
	x_view.Move(-x_positionX, -x_positionY);

	x_windowBackground.SetImage(x_data->GetImage("gui/login.png"));

	// Create the widgets
	x_widgets["labelusername"] = new XLabel(data, 24, 40, "Username:");
	x_widgets["textusername"] = new XTextField(data, 100, 40, 80);

	x_widgets["labelpassword"] = new XLabel(data, 24, 55, "Password:");
	x_widgets["textpassword"] = new XTextField(data, 100, 55, 80);
	x_widgets["textpassword"]->SetPassword(true);

	x_widgets["buttonsend"] = new XPushButton(data, 50, 16, 100, 80);

	x_widgets["labelversion"] = new XLabel(data, 8, 268, "");
	x_widgets["labelnewversion"] = new XLabel(data, 8, 278, "");
	
	// Set the default focus
	x_widgets["textusername"]->SetFocus(true);

	if (x_data->GetString("username") != "")
	{
		x_widgets["textusername"]->SetText(x_data->GetString("username"));
		x_widgets["textusername"]->SetFocus(false);
		x_widgets["textpassword"]->SetFocus(true);
	}
}

// Draws the window
void GLogin::Draw()
{
    if (x_visible)
    {
        XWindow::Draw();
    }
}

// Refresh the window
void GLogin::CheckState(const sf::Input &input)
{
	// Check the state of the widgets
	if (!x_manualOverride)
		XWindow::CheckState(input);

	if (x_widgets["buttonsend"]->state() == XG_ST_LBUTTON_RELEASED)
	{
		if (x_data->GetString("version") != x_data->GetString("newversion"))
		{
			x_data->SetString("popup-text", "Wrong version. Please update!");
			x_data->NewQueue("ui", "displaywindow", "popup");

		} else {

			x_data->NewPacket("login", x_widgets["textusername"]->GetText(), x_widgets["textpassword"]->GetText());
		}
	}

	x_widgets["labelversion"]->SetText("Client version: "+x_data->GetString("version"), true);
	x_widgets["labelnewversion"]->SetText("Newest version: "+x_data->GetString("newversion"), true);

	x_manualOverride = false;
}

// Check the queries of the widgets
void GLogin::CheckQuery()
{
	if (!x_data->queueEmpty("login"))
	{
		functions function = x_data->nextQueue("login");

		x_data->SetString("username", x_widgets["textusername"]->GetText());

		if (function.argument == "accept")
		{
			x_data->NewQueue("ui", "setscreen", "selectchar");
			
		} else if (function.argument == "refuse")
		{
			x_data->SetString("popup-text", "Wrong username/password. Try again!");
			x_data->NewQueue("ui", "displaywindow", "popup");
		}
	}
}
